package freedom.platform.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

import freedom.platform.dao.UserDao;
import freedom.platform.enums.YesOrNo;
import freedom.platform.model.User;
import freedom.struts.Pager;
import freedom.utils.ExampleMatcherUtils;

@Controller
@Scope("prototype")
@Results({@Result(name = "success", type = "redirectAction", params = {"actionName", "users"})})
public class UsersController extends ActionSupport {
    private static final long serialVersionUID = 1L;

    @Autowired
    private UserDao userDao;
    private User user = new User();
    private Pager<User> pager = new Pager<>();

    // GET /users
    public HttpHeaders index() {
        ExampleMatcher em = ExampleMatcher.matching();
        em = ExampleMatcherUtils.withIgnoreBlankValues(em, user);
        em = em.withMatcher(User.PROP_USERNAME, GenericPropertyMatchers.contains());
        em = em.withMatcher(User.PROP_PHONE, GenericPropertyMatchers.contains());
        Example<User> e = Example.of(user, em);

        List<Order> orders = new ArrayList<Order>(1);
        orders.add(new Order(Direction.DESC, User.PROP_UPDATE_TIME));
        Sort sort = new Sort(orders);

        PageRequest pr = pager.transform(sort);
        Page<User> page = userDao.findAll(e, pr);
        
        pager.complete(page);

        return new DefaultHttpHeaders("index").disableCaching();
    }

    // GET /users/1
    public HttpHeaders show() {
        user = userDao.getOne(user.getId());
        return new DefaultHttpHeaders("show").withETag(User.PROP_UPDATE_TIME).lastModified(user.getUpdateTime());
    }

    // GET /users/1/edit
    public String edit() {
        user = userDao.getOne(user.getId());
        return "edit";
    }

    // GET /users/new
    public String editNew() {
        user = new User();
        return "editNew";
    }

    // GET /users/1/deleteConfirm
    public String deleteConfirm() {
        return "deleteConfirm";
    }

    // DELETE /users/1
    public String destroy() {
        userDao.delete(user.getId());
        addActionMessage("User removed successfully");
        return "success";
    }

    // POST /users
    @Validations(
        requiredStrings = {
            @RequiredStringValidator(fieldName = User.PROP_EMAIL,
                message = "%{getText('pleaseInput','',getText('" + User.PROP_EMAIL + "'))}"),
            @RequiredStringValidator(fieldName = User.PROP_USERNAME,
                message = "%{getText('pleaseInput','',getText('" + User.PROP_USERNAME + "'))}"),
            @RequiredStringValidator(fieldName = User.PROP_PASSWORD,
                message = "%{getText('pleaseInput','',getText('" + User.PROP_PASSWORD + "'))}")},
        emails = {@EmailValidator(fieldName = User.PROP_EMAIL, message = "格式错误")})
    public HttpHeaders create() {
        if (null != userDao.findByUsername(user.getUsername())) {
            this.addFieldError(User.PROP_USERNAME, getText("user_existed"));
            return new DefaultHttpHeaders("input");
        }
        user.mark(true);
        user.setLockFlag(YesOrNo.NO);
        userDao.save(user);
        addActionMessage("New user created successfully");
        return new DefaultHttpHeaders("success").setLocationId(user.getId());
    }

    // PUT /users/1
    public String update() {
        user.mark(false);
        userDao.save(user);
        addActionMessage("User updated successfully");
        return "success";
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Pager<User> getPager() {
        return pager;
    }

    public void setPager(Pager<User> pager) {
        this.pager = pager;
    }

}
